package com.gwtgeo.ui.client.mvp.savemapas;


import java.util.Map;

import net.customware.gwt.dispatch.client.DispatchAsync;
import net.customware.gwt.presenter.client.EventBus;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasText;
import com.google.inject.Inject;
import com.gwtgeo.ui.client.mvp.map.MapPresenter;
import com.gwtgeo.ui.client.mvp.windowsmanager.WindowTypeEnum;
import com.gwtgeo.ui.client.mvp.windowsmanager.WindowedDisplay;
import com.gwtgeo.ui.client.mvp.windowsmanager.WindowedPresenter;
import com.gwtgeo.ui.shared.event.CloseWinModalEvent;
import com.gwtgeo.ui.shared.rpc.SaveDef;
import com.gwtgeo.ui.shared.rpc.SaveDefResult;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.HasClickHandlers;


public class SaveMapAsPresenter extends WindowedPresenter<SaveMapAsPresenter.Display> {

	private final DispatchAsync dispatcher;

	private final MapPresenter mapPresenter;

	public interface Display extends WindowedDisplay {
		HasClickHandlers getAcceptClick();

		HasClickHandlers getCancelClick();

		HasText getFileName();

		boolean validate();
	}

	@Inject
	public SaveMapAsPresenter(Display display, EventBus eventBus,
			MapPresenter mapPresenter, DispatchAsync dispatcher) {
		super(display, eventBus);
		this.dispatcher = dispatcher;
		this.mapPresenter = mapPresenter;
	}

	@Override
	public void init(Map<String, Object> params) {
	}

	@Override
	public WindowTypeEnum getType() {
		return WindowTypeEnum.SAVE_AS;
	}

	@Override
	protected void onBind() {
		super.onBind();
		this.registerHandler(display.getAcceptClick().addClickHandler(
				new ClickHandler() {

					@Override
					public void onClick(ClickEvent event) {
						if (display.validate()) {
							dispatcher.execute(new SaveDef(display
									.getFileName().getText(), mapPresenter
									.buildSaveableModel()),
									new AsyncCallback<SaveDefResult>() {

										@Override
										public void onFailure(Throwable caught) {
											// TODO PMA20100320 handle error.

										}

										@Override
										public void onSuccess(
												SaveDefResult result) {
											SC
													.say("Project "
															+ display
																	.getFileName()
																	.getText()
															+ " successfully saved.");
											eventBus.fireEvent(new CloseWinModalEvent(getType()));
										}

									});
						}
					}
				}));

		this.registerHandler(this.display.getCancelClick().addClickHandler(
				new ClickHandler() {

					@Override
					public void onClick(ClickEvent event) {
						eventBus.fireEvent(new CloseWinModalEvent(getType()));
					}
				}));
	}

	@Override
	protected void onRevealDisplay() {
	}

	@Override
	protected void onUnbind() {
	}
}